package com.my.study.structures.sparsearray;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/6/1 22:37
 **/
@Slf4j(topic = "c.SparseArray")
public class SparseArray {

    public static void main(String[] args) {
        // 创建一个二维数据 11 * 11
        int[][] chess = new int[11][11];
        chess[1][2] = 1;
        chess[2][3] = 2;
        for (int[] row : chess) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

        // 二维数组 -》稀疏数组
        //row col value
        int sum = 0;
        for (int i = 0; i < chess.length; i++) {
            for (int j = 0; j < chess[i].length; j++) {
                if (chess[i][j] != 0) {
                    sum++;
                }
            }
        }
        log.debug("sum = {}", sum);
        int[][] sparsArr = new int[sum+1][ 3];
        // 稀疏数组 第一行
        sparsArr[0][0] = chess.length;
        sparsArr[0][1] = chess[0].length;
        sparsArr[0][2] = sum;

        // 用于记录第一个非0数据
        int index = 0;
        for (int i = 0; i < chess.length; i++) {
            for (int j = 0; j < chess[i].length; j++) {
                if (chess[i][j] != 0) {
                    index++;
                    sparsArr[index][0] = i;
                    sparsArr[index][1] = j;
                    sparsArr[index][2] = chess[i][j];
                }
            }
        }

        System.out.println();
        for (int i = 0; i < sparsArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparsArr[i][0],sparsArr[i][1],sparsArr[i][2]);
        }



        // 稀疏数组 -> 二维数组
        int[][] chessArr = new int[sparsArr[0][0]][sparsArr[0][1]];
        for (int i = 1; i < sparsArr.length; i++) {
            chessArr[sparsArr[i][0]][sparsArr[i][1]] = sparsArr[i][2];
        }

    }
}
